<template>
    <div class="driver-manage-container">
        <div class="all-header">
            <div class="current-header">
                <div class="header-left">
                    <img class="driver-logo"
                        :src="basicSettingData?.logoImg || 'https://image.lutongjiakao.com/system/f40d3b7d52474f24b6863de7e8aa8631.png'"
                        alt="" />
                    <!-- <div class="driver-name">绿通驾</div> -->
                </div>
                <div class="header-right">
                    <el-popover ref="userMenuPopover" placement="bottom-end" :width="260" :hide-after="0" :offset="10"
                        trigger="hover" :show-arrow="false" popper-class="user-menu-popover"
                        popper-style="border: 1px solid var(--art-border-dashed-color); border-radius: calc(var(--custom-radius) / 2 + 4px); padding: 5px 16px; 5px 16px;">
                        <template #reference>
                            <div style="display: flex; justify-content: center; align-items: center">
                                <img class="cover"
                                    :src="userInfo.avatar || 'https://image.lutongjiakao.com/system/c456f65252df4d27b99acd8b7f3703c9.jpg'" />
                                <!-- <div>{{ userInfo.name }}</div> -->
                                <el-icon>
                                    <CaretBottom />
                                </el-icon>
                            </div>
                        </template>
                        <template #default>
                            <div class="user-menu-box">
                                <div class="user-head">
                                    <img class="cover"
                                        :src="userInfo.avatar || 'https://image.lutongjiakao.com/system/c456f65252df4d27b99acd8b7f3703c9.jpg'"
                                        style="float: left" />
                                    <div class="user-wrap">
                                        <span class="name">{{ userInfo.nickname }}</span>
                                        <span> ID: {{ userInfo.id }}</span>
                                    </div>
                                </div>
                                <ul class="user-menu">
                                    <li @click="goPage('/user/personalCenter')">
                                        <i class="menu-icon iconfont-sys">&#xe755;</i>
                                        <span class="menu-txt">{{ $t('topBar.user.userSet') }}</span>
                                    </li>
                                    <div class="line"></div>
                                    <div class="logout-btn" @click="loginOut">
                                        {{ $t('topBar.user.logout') }}
                                    </div>
                                </ul>
                            </div>
                        </template>
                    </el-popover>
                </div>
            </div>
        </div>

        <div class="driver-container">
            <div class="title">账号设置</div>
            <div class="container">
                <div class="list">
                    <div class="list-item">
                        <div>
                            <div class="subTitle">头像</div>
                            <div><img class="avatar"
                                    :src="userInfo.avatar || 'https://image.lutongjiakao.com/system/c456f65252df4d27b99acd8b7f3703c9.jpg'"
                                    alt="" /></div>
                        </div>
                        <el-upload class="avatar-uploader" :action="server" :headers="headers" :show-file-list="false"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <div class="link">去上传</div>
                        </el-upload>
                    </div>
                    <div class="list-item">
                        <div>
                            <div class="subTitle">联系人姓名</div>
                            <div>{{ userInfo.nickname }}</div>
                        </div>
                        <!--            <div class="link" @click="delAccount">注销账号</div>-->
                    </div>
                    <div class="list-item">
                        <div>
                            <div class="subTitle">手机号</div>
                            <div>{{ userInfo.phone }}</div>
                        </div>
                        <!--            <div class="link" @click="delAccount">注销账号</div>-->
                    </div>
                    <div class="list-item">
                        <div>
                            <div class="subTitle">登陆密码</div>
                            <div>******</div>
                        </div>
                        <div class="link" @click="passwordDialogVisible = true">去修改</div>
                    </div>
                </div>
            </div>

            <div class="back-btn" @click="goBack">返回</div>
        </div>

        <div class="protocol">
            <div class="line"></div>
            <div class="text">全面赋能驾校降本增效，全方位提升驾校数字化运营管理</div>
            <div class="line"></div>
        </div>

        <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500" :before-close="handleClosePassword"
            :close-on-click-modal="false">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
                <el-form-item label="当前密码" prop="currentPassword">
                    <el-input v-model="ruleForm.currentPassword" type="password" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="新密码" prop="password">
                    <el-input v-model="ruleForm.password" type="password" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="请确认新密码" prop="confirmPassword">
                    <el-input v-model="ruleForm.confirmPassword" type="password" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" :loading="editLoading" @click="editPasswordInfo">确认</el-button>
                    <el-button @click="closePasswordDialog">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import type { FormInstance, FormRules } from 'element-plus'
// import { editUserInfo, editPassword } from '@/api/ApiList'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
import { ref } from 'vue'
import { LoginMethod } from '@/api/LoginMethod'
// import { UserService } from '@/api/usersApi'

let server = `${import.meta.env.VITE_API_URL}files`
let { accessToken } = userStore
const headers = { Authorization: 'Brokerage ' + accessToken }

const { t } = useI18n()

const router = useRouter()

const userMenuPopover = ref()
const userInfo = computed(() => userStore.getUserInfo)

const passwordDialogVisible = ref(false)
const editLoading = ref(false)
const newLogo = ref()
const pollingTimer = ref<any>(null)
const basicSettingData = ref()

interface RuleForm {
    currentPassword: string
    password: string
    confirmPassword: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    currentPassword: '',
    password: '',
    confirmPassword: ''
})

const rules = reactive<FormRules<RuleForm>>({
    currentPassword: [
        {
            required: true,
            message: '不能为空',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '不能为空',
            trigger: 'blur'
        }
    ],
    confirmPassword: [
        {
            required: true,
            message: '不能为空',
            trigger: 'blur'
        }
    ]
})

const handleAvatarSuccess = (file: any) => {
    newLogo.value = file.data.url
    // editLogoImg()
}
//上传限制大小格式等
const beforeAvatarUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
        ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 20MB!!')
        return false
    }
}

const goPage = (path: string) => {
    router.push(path)
}

const closeUserMenu = () => {
    setTimeout(() => {
        userMenuPopover.value.hide()
    }, 100)
}

function goBack() {
    router.back()
}

function handleClosePassword() {
    passwordDialogVisible.value = false
}

function handleUnbind() {
    ElMessageBox.confirm('确定要解绑该账号吗？', '解绑账号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
    }).then(() => {
        // unbindWX()
    })
}

// async function unbindWX() {
//     const res = await editUserInfo({
//         id: userInfo.value.id,
//         status: 1,
//         userImg: ''
//     })
//     if (res.code === '00000') {
//         ElMessage.success('解绑成功')
//         await getUserInfo()
//     }
// }

// async function handleBind() {
//     try {
//         const res = await LoginMethod.wxAuthorization({})
//         if (res.code === '00000') {
//             const authWindow = window.open(res.msg, '_blank', 'width=500,height=700')

//             pollingTimer.value = setInterval(async () => {
//                 try {
//                     const res = await LoginMethod.getAuthorizationStatus({})
//                     if (res.code === '00000') {
//                         clearInterval(pollingTimer.value)
//                         pollingTimer.value = null

//                         // 关闭授权窗口（确保窗口还开着）
//                         if (authWindow && !authWindow.closed) {
//                             authWindow.close()
//                         }

//                         ElMessage.success('微信绑定成功')
//                         await getUserInfo()
//                     }
//                 } catch (err) {
//                     console.error('轮询失败', err)
//                 }
//             }, 1000)
//         }
//     } catch {
//     } finally {
//     }
// }

// 获取用户信息
// const getUserInfo = async () => {
//     if (userStore.isLogin) {
//         const res = await UserService.getUserInfo()
//         if (res.code === '00000') {
//             userStore.setUserInfo(res.data)
//         }
//     }
// }

// async function editLogoImg() {
//     const res = await editUserInfo({
//         id: userInfo.value.id,
//         userImg: newLogo.value
//     })
//     if (res.code === '00000') {
//         await getUserInfo()
//     }
// }

async function editPasswordInfo() {
    // try {
    //     editLoading.value = true
    //     const res = await editPassword({
    //         oldPassword: ruleForm.currentPassword,
    //         newPassword: ruleForm.password
    //     })
    //     if (res.code === '00000') {
    //         passwordDialogVisible.value = false
    //         ElMessage.success('修改成功')
    //     }
    // } catch (e) {
    // } finally {
    //     editLoading.value = false
    // }
}

function closePasswordDialog() {
    passwordDialogVisible.value = false
    ruleForm.currentPassword = ''
    ruleForm.password = ''
    ruleForm.confirmPassword = ''
}

// function delAccount() {
//   ElMessageBox.confirm('确定要注销该账号吗？', '注销账号', {
//     confirmButtonText: '确定',
//     cancelButtonText: '取消',
//     type: 'error'
//   }).then(() => {
//     ElMessage.success('注销成功')
//   })
// }

const loginOut = () => {
    closeUserMenu()
    setTimeout(() => {
        ElMessageBox.confirm(t('common.logOutTips'), t('common.tips'), {
            confirmButtonText: t('common.confirm'),
            cancelButtonText: t('common.cancel'),
            customClass: 'login-out-dialog'
        }).then(() => {
            userStore.logOut()
        })
    }, 200)
}
onMounted(() => {
    console.log(userInfo, 'userInfo')
})

onUnmounted(() => {
    if (pollingTimer.value) {
        clearInterval(pollingTimer.value)
    }

    let basicSettingInfo = JSON.parse(localStorage.getItem('lty-website-basic-type') || '{}')
    if (basicSettingInfo.title) {
        basicSettingData.value = basicSettingInfo
    }
})
</script>

<style lang="scss" scoped>
@use './style.scss';

.driver-manage-container {
    width: 100%;
    height: 100%;
    min-height: 100vh;
    display: flex;
    flex-direction: column;

    .all-header {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        max-height: 80px;
        // margin-bottom: 50px;
        border-bottom: 1px solid #f5f7fa;

        .current-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 1400px;
            height: 100px;

            .header-left {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                height: 100%;
                width: 130px;

                .driver-logo {
                    height: 42px;
                }

                .driver-name {
                    font-size: 20px;
                }
            }

            .header-right {
                display: flex;
                justify-content: center;
                align-items: center;

                .cover {
                    width: 30px;
                    height: 30px;
                    margin: 0 10px 0 0;
                    overflow: hidden;
                    background: #eee;
                    border-radius: 50%;
                }
            }
        }
    }

    .driver-container {
        flex: 1;
        padding-top: 32px;
        width: 100%;
        background-color: #f5f7fa;
        height: calc(100vh - 160px);
        font-size: 14px;
        display: flex;
        flex-direction: column;

        .title {
            font-weight: 500;
            font-size: 18px;
            text-align: center;
            padding: 20px 0 40px 0;
        }

        .container {
            width: 720px;
            margin: 0 auto;

            .list {
                background-color: #fff;
                height: 100%;
                border-radius: 8px;

                .list-item {
                    padding: 24px 40px;
                    border-bottom: 1px solid #f5f5f5;
                    font-size: 14px;

                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .wx-info {
                        display: flex;
                        align-items: center;
                    }

                    .subTitle {
                        margin-bottom: 10px;
                    }

                    .avatar {
                        width: 50px;
                        height: 50px;
                        border-radius: 50%;
                        margin-right: 10px;
                    }

                    .link {
                        color: var(--el-color-primary);
                        cursor: pointer;
                    }
                }
            }
        }

        .back-btn {
            width: 120px;
            height: 40px;
            margin: 0 auto;
            line-height: 40px;
            font-size: 14px;
            background-color: #fff;
            border-radius: 4px;
            display: flex;
            justify-content: center;
            margin-top: 50px;
            cursor: pointer;

            &:hover {
                color: var(--el-color-primary);
                background-color: var(--el-color-primary-light-9);
            }
        }
    }

    .protocol {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #b2b2b2;
        background-color: #f5f7fa;
        max-height: 80px;
        font-size: 14px;

        .line {
            background-color: #b2b2b2;
            width: 60px;
            height: 1px;
        }

        .text {
            padding: 0 20px;
        }
    }
}
</style>